package cn.yzgy.yzgyoa.common.handler;

import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.crsp.Urmf;
import cn.yzgy.yzgyoa.common.service.impl.SysAlarmServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局Exception处理
 *
 * @author Yqsen
 * @version 0.0.1
 * @since 2019-8-16 09:32:54
 */
@Slf4j
@ControllerAdvice
@RestControllerAdvice
@Order(2)
public class GeneralExceptionHandler {

    @Autowired
    private SysAlarmServiceImpl sysAlarmService;

    @ResponseBody
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Urmf notFoundException(NoHandlerFoundException e, HttpServletRequest request) {
        log.error("NOT_FOUND_EXCEPTION_HANDLER: Path:[{}] StackTrace:[{}] Message:[{}]", request.getRequestURI(), e.getStackTrace()[0],e.getMessage());
        return Urmf.fail(request.getRequestURI(), StatusCode.NOT_FOUND, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Urmf exceptionHandler(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        log.error("EXCEPTION_HANDLER: Path:[{}] StackTrace:[{}] Message:[{}]", request.getRequestURI(), e.getStackTrace()[0],e.getMessage());
        sysAlarmService.saveExceptions(e);
        return Urmf.fail(request.getRequestURI(), StatusCode.EXCEPTION, e.getMessage());
    }

}
